package pl.bristleback.server.bristle.mocks;

import org.apache.log4j.Logger;
import org.jwebsocket.api.WebSocketConnector;
import org.jwebsocket.api.WebSocketEngine;
import org.jwebsocket.config.xml.EngineConfig;
import org.jwebsocket.kit.PlugInResponse;
import org.jwebsocket.tcp.TCPConnector;
import org.jwebsocket.tcp.TCPEngine;
import org.jwebsocket.token.JSONToken;
import org.jwebsocket.token.Token;
import pl.bristleback.server.bristle.config.BristleConstants;
import pl.bristleback.server.bristle.mocks.actions.RemoteActionMock;
import pl.bristleback.server.bristle.rights.ConnectorRightsSet;

import java.net.Socket;
import java.util.ArrayList;
import java.util.List;

/**
 * Mock factory.
 * <p/>
 * Created on: 2010-09-03 16:30:57 <br/>
 *
 * @author Wojciech Niemiec
 */
public class BristleServerMockFactory {
  private static Logger log = Logger.getLogger(BristleServerMockFactory.class.getName());

  public static final String MOCK_TOKEN_KEY = "mockKey";
  public static final String MOCK_TOKEN_VALUE = "mockValue";

  private static final String REMOTE_ACTIONS_MOCKS_PACKAGE = "pl.bristleback.server.bristle.mocks.actions";

  private static final String DOMAIN_NAME = "pl.bristleback.server.bristle";

  public WebSocketEngine getTCPMockEngine() {
    return new TCPEngine(getEngineConfig());
  }

  private EngineConfig getEngineConfig() {
    List<String> domains = new ArrayList<String>();
    domains.add(DOMAIN_NAME);
    return new EngineConfig("tcp0", "org.jwebsocket.tcp.engines.TCPEngine",
      "jWebSocketTCPEngine-1.0.jar", 8787, 0, "aKeyStore", "aKeyStorePassword", "aContext", "aServlet", 100, 1048840, domains);
  }

  public Token getMockToken(String namespace, String actionName) {
    Token token = new JSONToken(namespace, JSONToken.TT_EVENT);
    token.setString(BristleConstants.ACTION_NAME_TOKEN_VARIABLE, actionName);
    token.setString(MOCK_TOKEN_KEY, MOCK_TOKEN_VALUE);
    return token;
  }

  public PlugInResponse getMockPluginResponse() {
    return new PlugInResponse();
  }

  public WebSocketConnector getMockConnector(WebSocketEngine engine, boolean hasRights) {
    WebSocketConnector connector = new TCPConnector(engine, new Socket());
    connector.setVar(BristleConstants.CONNECTOR_RIGHTS_SET_VARIABLE_NAME, getRights(hasRights));
    return connector;
  }

  private ConnectorRightsSet getRights(boolean hasRights) {
    ConnectorRightsSet rightsSet = new ConnectorRightsSet();
    if (hasRights) {
      rightsSet.addRight(RemoteActionMock.ACTION_RIGHTS);
    }
    return rightsSet;
  }

  public String getRemoteActionsMockPackage() {
    return REMOTE_ACTIONS_MOCKS_PACKAGE;
  }
}
